#!/usr/bin/python
# 2009 (c) Mikhail Borovoy
import sys
import gzip
from cgi import escape
import pyproj
from optparse import OptionParser

#KML_NAMESPACE = "http://www.opengis.net/kml/2.2"
feet2meters = 0.3048

parser = OptionParser()
parser.add_option("-i", "--input", dest="input_file", help="input APT file", metavar="FILE")
parser.add_option("-o", "--output", dest="output_file", help="output KML file", metavar="FILE")
#parser.add_option("-c", "--geocentric", dest="geocentric", action="store_true", default=False, help="use simple geocentric model (not ready yet)")
parser.add_option("-a", "--airport", dest="airport", help="aiports delimited by comma (not ready yet)")

(options, args) = parser.parse_args()
#sys.stderr.write("%s\n" % options.geocentric)

if options.input_file == None:
    f = sys.stdin
else:
    if options.input_file.endswith(('.gz', '.GZ')):
        f = gzip.open(options.input_file, 'rb')
    else:
        f = open(options.input_file)
    
if options.output_file == None:
    f2 = sys.stdout
else:
    f2 = open(options.output_file, 'w')

f2.write('''<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
  <name>FG Airports</name>
  <Style id="RWY_BluePoly">
    <LineStyle>
      <width>1.5</width>
    </LineStyle>
    <PolyStyle>
      <color>7dff0080</color>
    </PolyStyle>
  </Style>
''')

def add_poly(p1, p2, p3, p4, s):
    s = """
<Placemark>
  <name>%s</name>
  <styleUrl>%s</styleUrl>
  <Polygon>
    <outerBoundaryIs>
      <LinearRing>
        <coordinates>
""" % (s[3], "RWY_BluePoly")
    s += "%f,%f,0\n" % (p1[0], p1[1])
    s += "%f,%f,0\n" % (p2[0], p2[1])
    s += "%f,%f,0\n" % (p3[0], p3[1])
    s += "%f,%f,0\n" % (p4[0], p4[1])
    s += "%f,%f,0\n" % (p1[0], p1[1])
    s += """
        </coordinates>
      </LinearRing>
    </outerBoundaryIs>
  </Polygon>
</Placemark>
"""
    f2.write(s)

g = pyproj.Geod(ellps='WGS84')
ap = None
for line in f:
    s = line.split()
    if len(s) >= 5 and s[0] == "1":
        if ap != None:
            f2.write("</Folder>\n")
        ap = s[4]
        sys.stderr.write("Processing " + ap + "\n")
        f2.write("""
<Folder>
  <name>%s</name>
  <description>%s</description>
""" % (escape(s[4]), escape(s[5]))
                )
    if len(s) >= 1 and s[0] == "99" and ap != None:
        f2.write("</Folder>")
    if (len(s) >= 15) and (s[0] == "10"):
        lon = float(s[1])
        lat = float(s[2])
        az = float(s[4])
        length = float(s[5]) * feet2meters
        width = float(s[8]) * feet2meters
        a  = g.fwd(lat, lon, az + 90, width/2.0) # get new lat, lon, back azimuth
        p1 = g.fwd(a[0], a[1], az, length/2.0)
        p2 = g.fwd(a[0], a[1], az+180, length/2.0)
        a  = g.fwd(lat, lon, az - 90, width/2.0)
        p3 = g.fwd(a[0], a[1], az+180, length/2.0)
        p4 = g.fwd(a[0], a[1],  az, length/2.0)
        add_poly(p1, p2, p3, p4, s)
f.close()

f2.write('''
  </Document>
</kml>
''')
f2.close()


def main():
    pass

if __name__ == "__main__":
    #main()
    pass
